package com.hjj.hello.spring.boot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class SystemController {

    /**
     * 跳转到登录页
     * @return
     */
    @RequestMapping(value = "login" , method = RequestMethod.GET)
    public String login(){
        return "login";
    }

    /**
     * 登录逻辑
     * @return
     */
    @RequestMapping(value = "login" , method = RequestMethod.POST)
    public String login(String username , String password , Model model){

        /**
         * 使用 Shiro 完成认证编写
         */
        // 1 . 获取Subject
        Subject subject = SecurityUtils.getSubject();
        // 2 . 封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        //执行登录方法
        try {
            subject.login(token);

            return "redirect:/index";
        } catch (UnknownAccountException e) { //有异常则登录失败
            //e.printStackTrace();
            //UnknownAccountException表示用户名不存在
            System.out.println("UnknownAccountException=====>用户登录认证失败:用户名不存在");
            model.addAttribute("msg","用户名不存在");
            return "login";
        } catch (IncorrectCredentialsException e) { //有异常则登录失败
            //e.printStackTrace();
            //IncorrectCredentialsException 密码错误
            System.out.println("UnknownAccountException=====>用户登录认证失败:密码错误");
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }

    /**
     * Shiro 为授权页面
     */
    @RequestMapping(value = "unAuth" , method = RequestMethod.GET)
    public String unAuth(){
        return "unAuth";
    }
}
